#include "LevelGrid.hpp"

char LevelGrid::_GetGridCharAtCursorPosition(const Vector& cursor_position)
{
	return 't';
}

Vector LevelGrid::_GetGridElementPositionAtCursorPosition(const Vector& cursor_position)
{
	// Determine the row and column number of the element that the cursor is over.
	Vector grid_space_position = cursor_position - _position;
	int row = grid_space_position.y / _element_height;
	int col = grid_space_position.x / _element_width;

	// Add the grid position so that the coordinates are relative to screen space.
	return _position + Vector(col * _element_width, row * _element_height);
}

bool LevelGrid::_IsCursorOverGrid(const Vector& cursor_position)
{
	float grid_left_bound = _position.x;
	if(cursor_position.x < grid_left_bound)
		return false;

	float grid_upper_bound = _position.y;
	if(cursor_position.y < grid_upper_bound)
		return false;

	float grid_right_bound = _position.x + _grid_rows * _element_width;
	if(grid_right_bound < cursor_position.x)
		return false;

	float grid_lower_bound = _position.y + _grid_columns * _element_height;
	if(grid_lower_bound < cursor_position.y)
		return false;

	return true;
}

LevelGrid::LevelGrid()
	: _element_width(64.0f),
	  _element_height(64.0f),
	  _grid_rows(5),
	  _grid_columns(5),
	  _grid(_grid_columns, std::vector<char>(_grid_rows, 't')),
	  _position(110.0f, 110.0f)
{
	_tower_grid.reset(al_load_bitmap("../images/level_tower.png"), [](ALLEGRO_BITMAP* p){al_destroy_bitmap(p);});
}

void LevelGrid::PlaceTowerAtLocation(const Vector& cursor_position)
{
	if(!_IsCursorOverGrid(cursor_position))
	{
		// We can't place a tower here because this position isn't within the grid.
		return;
	}

	if(!_GetGridCharAtCursorPosition(cursor_position) == _TOWER_CHAR)
	{
		// We can't place a tower here because this grid element is of a type
		// other than tower. E.g. spawn, path, objective, etc...
		return;
	}

	Vector grid_element_position = _GetGridElementPositionAtCursorPosition(cursor_position);

	// The grid element's position is the upper left corner of the grid element. We must apply an
	// offset to place the tower in the middle of the grid element.
	_towers.push_back(TestArrow(grid_element_position + Vector(_element_width/2, _element_height/2)));
}

void LevelGrid::Draw()
{
	for(unsigned row = 0; row < _grid.size(); ++row)
		for(unsigned col = 0; col < _grid[row].size(); ++col)
		{
			Vector element_position(_position.x + col * _element_width, _position.y + row * _element_height);
			switch(_grid[row][col])
			{
			case _TOWER_CHAR:
				al_draw_bitmap(_tower_grid.get(), element_position.x, element_position.y, 0);
				break;
			default:
				break;
			}
		}

	for(unsigned i = 0; i < _towers.size(); ++i)
	{
		_towers[i].DrawFacing(Vector(0.0f, 0.0f));
	}
}